#include "GuiContext.h"

#include "LoopStatusControlPage.h"
#include "PasswordPage.h"

#include "Authenticator.h"


GuiContext::GuiContext() : WorkerBase(REFRESH_PERIOD), pool(1000), mauthenticator(AuthenticatorSingleton::instance()) {

    this->setWorkPool(&pool);

    refreshPageFunction = std::bind(&GuiContext::refreshPage, this);
    mTimeoutElement = Task{TaskType_t::CALLBACK, &refreshPageFunction};
}



void GuiContext::run() {

    Keypad& keyPad = KeypadSingleton::instance();
    /*
    KeyCode keyCode;
    while(loop && (keyCode = keyPad.listen())) {
        onKeyPressed(keyCode);
    }
    */

    getWorkThread().start();
    keyPad.listen();
}


int GuiContext::onKeyPressed(const KeyCode& keyCode) {
    int result = 0;
//        LOG_DEDUG("%s:%d", __func__, keyCode);
    if (!mauthenticator.mpermit && KeyCode::DOWN != keyCode && KeyCode::UP != keyCode && KeyCode::ENTER != keyCode && KeyCode::FORCE_SYNC_LED != keyCode) {
        if (&*pActivePage != pPasswordPage) {
            setPage(pPasswordPage->getPageNumber() - 1);
            result = 2;
            return result;
        }

        result = pActivePage->onKeyPressed(keyCode);
    } else {

        if (KeyCode::CHANNEL_MAX >= keyCode) {
            result = pLoopStatusControlPage->onChannelKeyPressed(keyCode);
        } else if (KeyCode::FORCE_SYNC_LED == keyCode) {
            LoopControlInfoPtr loopControlInfoPtr = LoopManagerSingleton::instance().getLoopStatus();
            usleep(50*1000);
            pLoopStatusControlPage->onLoopChanged(loopControlInfoPtr);
        } else {
            bool focus = pActivePage->focus;

            if (focus) {
                result = pActivePage->onKeyPressed(keyCode);
            } else {
                result = this->Base::onKeyPressed(keyCode);

                if (!result) {
                    result = pActivePage->onKeyPressed(keyCode);
                }
            }
        }

    }

    if (2 == result) {
        refreshPage();
    }

    return result;
}


void GuiContext::refreshPage() {
    mTimeout = REFRESH_PERIOD;

    pActivePage->refreshPage();
}
